#include "thread/thread_pool.h"
#include "base/atomic.h"

namespace weilin {
	ThreadPool::ThreadPool(const uint32_t& thread_num) :
		m_thread_num(thread_num) 
	{
	}

	ThreadPool::~ThreadPool()
	{
		Stop(STOP_PEACE);
	}
	void ThreadPool::Init()
	{
        	m_io_service_sp = boost::make_shared<boost::asio::io_service>();
        	m_service_work_sp.reset(new (std::nothrow)boost::asio::io_service::work(*m_io_service_sp));
	}

	void ThreadPool::Start()
	{
		for (uint32_t index = 0; index < m_thread_num; index++)
		{
			m_thread_group.create_thread(boost::bind(&ThreadPool::Run, shared_from_this()));
		}
	}

	void ThreadPool::Stop(const StopMthod& stop_method)
	{
		if (stop_method == STOP_PEACE)
		{
			m_service_work_sp.reset();
		}
		else
		{
			m_io_service_sp->stop();
			m_io_service_sp.reset();
		}

		m_thread_group.join_all();
	}

	void ThreadPool::Run()
	{
		m_io_service_sp->run();
	}

}
